<template>
  <div class="half-price">
    <a-form-model
      class="half-price-form"
      ref="ruleForm"
      :model="formData"
      :rules="rules"
      :label-col="{ span: 4 }"
      :wrapper-col="{ span: 20 }">
      <a-form-model-item prop="type">
        <template slot="label">
          <span style="color: red">*</span>活动类型
        </template>
        <a-radio-group :disabled="handle == 'view'" v-model="formData.type">
          <a-radio :value="1">第二件半价</a-radio>
          <a-radio :value="2">买一赠一</a-radio>
        </a-radio-group>
      </a-form-model-item>
      <a-form-model-item prop="activityName">
        <template slot="label">
          <span style="color: red">*</span>活动名称
        </template>
        <a-input
          :maxLength="20"
          allow-clear
          style="width:300px"
          v-model="formData.activityName"
          :disabled="handle == 'view'"
          placeholder="请输入活动名称" />
      </a-form-model-item>
      <a-form-model-item prop="startTime">
        <template slot="label">
          <span style="color: red">*</span>活动开始时间
        </template>
        <a-date-picker
          style="width:300px"
          allow-clear
          v-model="formData.startTime"
          :disabled="handle == 'view'"
          :disabled-date="disabledStartDate"
          show-time
          format="YYYY-MM-DD HH:mm:ss"
          value-format="YYYY-MM-DD HH:mm:ss"
          placeholder="请选择开始时间"
          @openChange="handleStartOpenChange" />
      </a-form-model-item>
      <a-form-model-item prop="endTime">
        <template slot="label">
          <span style="color: red">*</span>活动结束时间
        </template>
        <a-date-picker
          style="width:300px"
          allow-clear
          v-model="formData.endTime"
          :disabled="handle == 'view'"
          :disabled-date="disabledEndDate"
          show-time
          format="YYYY-MM-DD HH:mm:ss"
          value-format="YYYY-MM-DD HH:mm:ss"
          placeholder="请选择结束时间"
          :open="endOpen"
          @openChange="handleEndOpenChange" />
      </a-form-model-item>
      <a-form-model-item prop="goodsIds">
        <template slot="label">
          <span style="color: red">*</span>活动商品
        </template>
        <a-button :disabled="handle == 'view'" type="link" @click="chooseGoodsShow=true">{{ selectedListKeys.length == 0 ? '请选择商品' : '重新选择商品' }}</a-button>
      </a-form-model-item>
      <a-form-model-item prop="displayRules">
        <template slot="label">
          <span style="color: red">*</span>活动页规则展示
        </template>
        <a-radio-group
          v-model="formData.displayRules"
          :disabled="handle == 'view'">
          <a-radio :style="radioStyle" :value="1">默认文案
            <p class="form-tips">根据优惠设置自动生成规则文案，在活动页顶部展示</p>
          </a-radio>
          <a-radio :style="radioStyle" :value="2">自定义图片
            <p class="form-tips">用自制的图片在活动页顶部展示（无默认文案）</p></a-radio>
        </a-radio-group>
      </a-form-model-item>
      <a-form-model-item v-if="formData.displayRules == 2" prop="imageAdr">
        <template slot="label">
          <span style="color: red">*</span>上传图片
        </template>
        <upload-image
          v-model="formData.imageAdr"
          :disabled="handle == 'view'">
          <img v-if="formData.imageAdr" :src="formData.imageAdr" />
          <div v-else>
            <a-icon type="plus" />
          </div>
        </upload-image>
      </a-form-model-item>
      <a-form-model-item label="活动说明" prop="activityExplain">
        <a-textarea
          rows="8"
          placeholder="请输入活动说明"
          style="width:500px"
          v-model="formData.activityExplain"></a-textarea>
        <!-- <p class="form-tips">多件商品都参与活动时，价格低的商品享受半价优惠。此优惠可循环叠加。<br />例：买了1个甜筒（2元）和1支雪糕（3元），则甜筒享受半价优惠。</p>
        <p class="form-tips">第2件0元<br />多件商品都参与活动时，价格低的商品享受免单优惠。此优惠可循环叠加。<br />例：买了1张面膜A（30元）和1张面膜B（15元），则面膜B享受免单优惠。</p> -->
      </a-form-model-item>

      <a-form-model-item :wrapper-col="{ span: 14, offset: 4 }">
        <a-col :offset="2">
          <a-space>
            <a-button v-if="handle != 'view'" type="primary" @click="submitData()">提交保存</a-button>
            <a-button @click="handleCancel">{{ handle == 'view' ? '返回' : '取消'}}</a-button>
          </a-space>
        </a-col>
      </a-form-model-item>
    </a-form-model>

    <CommodityList :visible="chooseGoodsShow" :selectedKeys="selectedListKeys" @cancel="chooseGoodsShow=false" @submit="handleCommoditySubmit"></CommodityList>

  </div>
</template>

<script>
import deepCopy from '@/utils/deepCopy'
import { cloneDeep } from "lodash";
import moment from 'moment'
import CommodityList from './../components/CommodityList';
const formData={
  id: '',
  activityStatus: 1,
  type: 1,
  activityName: '',
  startTime: '',
  goodsIds: '',
  displayRules: 1,
  imageAdr: '',
  activityExplain: '多件商品都参与活动时，价格低的商品享受半价优惠。此优惠可循环叠加。\n例：买了1个甜筒（2元）和1支雪糕（3元），则甜筒享受半价优惠。\n\n第2件0元\n多件商品都参与活动时，价格低的商品享受免单优惠。此优惠可循环叠加。\n例：买了1张面膜A（30元）和1张面膜B（15元），则面膜B享受免单优惠。'
}
export default {
  components: {
    CommodityList
  },
  computed: {
    // 操作类型
    handle() {
      return this.$route.query.handle || "";
    },
    // 活动id
    id() {
      return this.$route.query.id || "";
    },
  },
  data() {
    return {
      formData,
      rules: {},
      disabled: false,
      endOpen: false,
      chooseGoodsShow: false,
      selectedListKeys:[],
      radioStyle: {
        display: 'block',
        height: 'auto',
        lineHeight: '30px',
      }
    };
  },
  created() {
    if(this.id){
      this.getDetail(this.id)
    }
    this.resetData()
  },
  mounted() {},
  methods: {
    moment,
    //重置
    resetData(){
      this.formData=deepCopy(formData);
    },
    // 获取活动详情
    async getDetail(id) {
      let res = await this.$get('/marketing/activity/id',
        { id },
        { baseURL: `${location.origin}/goldenhome/seckill/admin` });
      if(res && res.returnCode=='1000'){
        if(res.dataInfo){
          this.formData = cloneDeep(res.dataInfo);
          if(this.formData.goodsIds) this.selectedListKeys = this.formData.goodsIds.split(',')
        }
      }
    },
    // 开始时间不能小于当前时间
    disabledStartDate(current) {
      return current < moment().subtract(1, "days");
    },
    // 结束时间不能小于开始时间
    disabledEndDate(current) {
      return current < moment(this.formData.startDate)
    },
    // 是否打开结束时间组件
    handleStartOpenChange(open) {
      if (!open) {
        this.endOpen = true;
      }
    },
    // 结束时间组件
    handleEndOpenChange(open) {
      this.endOpen = open;
    },
    // 选择商品
    handleCommoditySubmit(selectedKeys){
      console.log('selectedKeys',selectedKeys);
      this.formData.goodsIds=selectedKeys.join(',');
      this.selectedListKeys=selectedKeys;
      this.chooseGoodsShow=false;
    },
    // 返回活动列表
    back() {
      this.$router.push({
        name: "MarketingCampaign",
        query: {},
      });
    },
    handleCancel(){
      console.log('取消')
      this.back()
    },
    // 提交
    async submitData() {
      // 验证活动类型
      if(!this.formData.type) {
        return this.$message.error('请选择活动类型');
      }
      // 验证活动名称
      if(!this.formData.activityName) {
        return this.$message.error('请输入活动名称');
      }
      // 验证活动时间
      if(!this.formData.startTime) {
        return this.$message.error('请选择活动开始时间');
      }
      if(moment(this.formData.startTime).unix() < moment().subtract(1, "days").unix()) {
        return this.$message.error('活动开始时间不能小于当前时间');
      }
      if (!this.formData.endTime) {
        return this.$message.error('请选择活动结束时间');
      }
      if(moment(this.formData.startTime).unix() > moment(this.formData.endTime).unix()) {
        return this.$message.error('活动结束时间不能小于活动开始时间');
      }
      // 验证活动商品
      if(!this.formData.goodsIds) {
        return this.$message.error('请选择活动商品');
      }
      // 验证活动页规则展示
      if(!this.formData.displayRules) {
        return this.$message.error('请选择活动页规则展示');
      }
      if(this.formData.displayRules == 2) {
        if(!this.formData.imageAdr) {
          return this.$message.error('请上传图片');
        }
      }
      
      let url = ''
      switch (this.handle) {
        case 'add':
          url = '/marketing/activity/add'
          break;
        case 'edit':
          url = '/marketing/activity/update'
          break;
      }
      let res = await this.$post(url,
        this.formData,
        { baseURL: `${location.origin}/goldenhome/seckill/admin` });
      if(res && res.returnCode=='1000'){
        this.back()
        return this.$message.success('保存成功！');
      } else{
        return this.$message.error('保存失败！');
      }
    }
  }
};
</script>

<style lang="less"></style>
